package com.liuda066.forumssm.services.impl;

import com.liuda066.forumssm.common.AppResult;
import com.liuda066.forumssm.common.ResultCode;
import com.liuda066.forumssm.dao.UserMapper;
import com.liuda066.forumssm.exception.ApplicationException;
import com.liuda066.forumssm.model.User;
import com.liuda066.forumssm.services.IUserService;
import com.liuda066.forumssm.utils.MD5Utils;
import com.liuda066.forumssm.utils.StringUtils;
import com.liuda066.forumssm.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/9/1 14:24
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectByUsername(String username) {
        //非空校验
        if(StringUtils.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByUsername(username);
        return user;
    }

    @Override
    public void createNormalUser(User user) {
        if (user == null || StringUtils.isEmpty(user.getUsername()) ||
                StringUtils.isEmpty(user.getNickname()) || StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getSalt())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existsUser = selectByUsername(user.getUsername());
        if  (existsUser != null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username = "+user.getUsername());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        if(user.getGender()==null || user.getGender() <0 || user.getGender() >2){
            user.setGender((byte) 2);
        }
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);

        Date date =new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insertSelective(user);
        if (row !=1){
            log.warn(ResultCode.FAILED_CREATE.toString()+"username = "+user.getUsername());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE) );
        }
        log.info("新增用户 : "+user.getUsername());
    }

    @Override
    public User login(String username, String password) {
        User user = selectByUsername(username);
        if (user == null){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        String encryptPassword = MD5Utils.md5Salt(password,user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.info(ResultCode.FAILED_LOGIN.toString() + "username : "+username+",password = "+password);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }

    @Override
    public User selectById(Long Id) {
        return userMapper.selectByPrimaryKey(Id);
    }

    @Override
    public void modifyInfo(User user) {
        // 非空校验
        if (user == null ||user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户基本信息
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser ==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 定义一个标识
        boolean checkAttr = false;
        // 定义一个更新对象
        User updateUser = new User();
        // 设置Id
        updateUser.setId(user.getId());
        // 更新时间
        updateUser.setUpdateTime(new Date());
        // 处理username
        if (!StringUtils.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())){
            // 如果username不为空，那么则需要更新
            // 1. 查询当前数据库中是否存在相同的用户名
            User checkUser = userMapper.selectByUsername(user.getUsername());
            if (checkUser != null){
                // 用户名已存在，抛出异常
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            // 设置要更新用户名
            updateUser.setUsername(user.getUsername());
            // 设置参数检查标识
            checkAttr = true;
        }
        // 处理nickname
        if (!StringUtils.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkAttr= true;
        }
        // 处理邮箱
        if (!StringUtils.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttr= true;
        }
        // 处理电话号码
        if (!StringUtils.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr= true;
        }
        // 处理个人简介
        if (!StringUtils.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAttr= true;
        }
        // 处理性别
        if (user.getGender() != null
                && user.getGender().longValue() != existsUser.getGender().longValue()){
            updateUser.setGender(user.getGender());
            if (updateUser.getGender() <0 || updateUser.getGender()>2){
                updateUser.setGender((byte) 2);
            }
            checkAttr=true;
        }
        // 处理图像
        if (user.getAvatarUrl() != null
                && !Objects.equals(user.getAvatarUrl(), existsUser.getAvatarUrl())){
            updateUser.setAvatarUrl(user.getAvatarUrl());

            checkAttr=true;
        }
        // 如查所有的参数都为空
        if (!checkAttr){
            log.warn("用户更新时，参数为空，userid = "+user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE +"参数为空"));
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn("用户更新时，受影响的行数不等于 1 ，"+ResultCode.ERROR_SERVICES.toString());
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        User user = userMapper.selectByPrimaryKey(id);
        //用户不存在
        if (user == null){
            log.info(ResultCode.FAILED_UNAUTHORIZED.toString()+"user id :" +id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
        }
        //原密码校验
        String oldEncryptPassword = MD5Utils.md5Salt(oldPassword,user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString()+"username :"
                    +user.getUsername()+", password = "+oldPassword);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //封装
        String salt = UUIDUtils.UUID_32();
        String encryptPassword = MD5Utils.md5Salt(newPassword,salt);
        User modifyUser = new User();
        modifyUser.setId(user.getId());
        modifyUser.setPassword(encryptPassword);
        modifyUser.setSalt(salt);
        modifyUser.setUpdateTime(new Date());

        //更新
        userMapper.updateByPrimaryKeySelective(modifyUser);
        log.info("用户密码修改成功："+user.getUsername());
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id<0){
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString()+"userId : "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser= new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString()+"受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id<0){
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString()+"userId : "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser= new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);

        if (updateUser.getArticleCount() < 0){
            updateUser.setArticleCount(0);
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString()+"受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
